package com.common.www.controller.tabulation;


import com.alibaba.fastjson.JSON;
import org.springframework.boot.base.jpa.service.IBaseService;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.programme.TabulationExtracting;
import com.common.www.bean.entity.project.Project;
import com.common.www.bean.entity.tabulation.*;
import com.common.www.controller.base.DefaultCrudController;
import com.common.www.data.NetCode;
import com.common.www.service.project.ProjectService;
import com.common.www.service.tabulation.AllTabulationService;
import com.common.www.service.tabulation.InnerBidBaseTabulationService;
import com.common.www.service.programme.TabulationExtractingService;
import com.common.www.service.tabulation.InnerSummaryService;
import com.common.www.utils.ParamsUtils;
import com.common.www.utils.R;
import com.common.www.utils.office.ImportExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping(value = {"mgt/innerBidBaseTabulation"})
@Api(tags = "MGT 后台内线标底清单管理")
public class MGTInnerBidBaseTabulationController extends DefaultCrudController<InnerBidBaseTabulation,Long> {

    @Autowired
    private InnerBidBaseTabulationService innerBidBaseTabulationService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private TabulationExtractingService extractingService;
    @Autowired
    private InnerSummaryService innerSummaryService;
    @Autowired
    private AllTabulationService allTabulationService;

    protected IBaseService<InnerBidBaseTabulation,Long> getService() {
        return innerBidBaseTabulationService;
    }


    @ApiOperation("保存单条内线标底清单")
    @RequestMapping(value = "/saveByJson", method = RequestMethod.POST)
    public Result saveByJson(@RequestBody InnerBidBaseTabulation innerTabulation) {
        if(innerTabulation.getId()!=null){
            innerBidBaseTabulationService.calculation(innerTabulation);
            innerBidBaseTabulationService.save(innerTabulation);
        }
        return R.ok(innerTabulation);
    }


    @ApiOperation("修改单个内线标底的分析分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "json", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/modifyFenXiFenLei", method = RequestMethod.POST)
    public Result saveByBatchModify(String json) {
        InnerBidBaseTabulation tabulation = JSON.parseObject(json, InnerBidBaseTabulation.class);
        if (tabulation.getId() != null) {
            InnerBidBaseTabulation existing = innerBidBaseTabulationService.getByIdLogic(tabulation.getId());
            if (existing != null) {
                // 如果存在，则更新现有对象的属性
                BeanUtils.copyProperties(tabulation, existing, "id");
                // 然后保存更新后的对象
                innerBidBaseTabulationService.saveAndFlush(existing);
            }
        }
        return R.ok(tabulation);
    }


    @ApiOperation("自动更正内线标底清单工作内容")
    @RequestMapping(value = "/saveAutoCorrect", method = RequestMethod.POST)
    public Result saveAutoCorrect(@RequestBody List<InnerBidBaseTabulation> tabulationList) {
        if (tabulationList != null && tabulationList.size() > 0) {
            for (InnerBidBaseTabulation tabulation : tabulationList) {
                //按 “分类、项目名称”来确定内线清单对应全系清单中的内容，匹配到多个数据时取其中一个
                List<AllTabulation> allTabulations = allTabulationService.getRepository().findByFlagAndNameAndFenLei(1, tabulation.getName(), tabulation.getFenLei());
                if (allTabulations == null || allTabulations.size() == 0) {
                    continue;
                } else {
                    Integer correct = 0;
                    for (AllTabulation a : allTabulations) {
                        if (StringUtils.isNotEmpty(tabulation.getModelCode())){
                            if (a.getModelCode().equals(tabulation.getModelCode())) {
                                correct++;
                            }
                        }else {
                            if (StringUtils.isEmpty(a.getModelCode())) {
                                correct++;
                            }
                        }
                    }
                    if (correct == 0) {
                        tabulation.setModelCodeError(1);
                    } else {
                        tabulation.setModelCodeError(2);
                    }
                    //修正工作内容
                    if (allTabulations.get(0).getGongZuoNeiRong().equals(tabulation.getGongZuoNeiRong())) {
                        tabulation.setGongZuoNeiRong(allTabulations.get(0).getGongZuoNeiRong());
                        tabulation.setUnit(allTabulations.get(0).getUnit());
                        tabulation.setNeiRongError(2);
                    }
                }
            }
        }
        innerBidBaseTabulationService.save(tabulationList);
        return R.ok(tabulationList);
    }


    @ApiOperation("批量删除（逻辑删除）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public Result batchDelete(Long[] ids) {
        if (ParamsUtils.isInputEmpty(ids)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        innerBidBaseTabulationService.deleteByIdsLogic(ids);
        return R.ok();
    }

    @ApiOperation("按项目删除对应标底信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "String", defaultValue = ""),
            @ApiImplicitParam(name = "bidType", value = "String", defaultValue = ""),
    })
    @Transactional
    @RequestMapping(value = "/deletesByProjectToType", method = RequestMethod.POST)
    public Result deletesByProjectToType(Long projectId,Integer bidType) {
        if (ParamsUtils.isInputEmpty(projectId,bidType)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        innerBidBaseTabulationService.getRepository().deleteByProjectIdAndBidType(projectId,bidType);

        Integer jieDuan = 1;
        if (bidType == 2){
            jieDuan = 7;
        }
        extractingService.getRepository().deleteByProjectIdAndInnerOuterTypeAndJieDuan(projectId,1,jieDuan);
        innerSummaryService.getRepository().deleteByProjectIdAndJieDuan(projectId,jieDuan);
        return R.ok();
    }


    @ApiOperation(value = "导入内线标底、实施标底清单", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/importBd", produces = {"application/json"}, method = RequestMethod.POST)
    public Result importBd(MultipartFile file,Long projectId,Integer bidType) throws Exception {
        Project project = projectService.findOne(projectId);
        InputStream inputStream = file.getInputStream();
        String fileName = file.getOriginalFilename();
        Workbook workbook = new ImportExcelUtil().getWorkbook(inputStream, fileName);
        List<InnerBidBaseTabulation> listImport = innerBidBaseTabulationService.importSimulate(workbook);
        //整理listImport的数据格式
        List<InnerBidBaseTabulation> listArrange = new ArrayList<>();

        String itemName = null;
        String lastNonNullOriginalTypeName = null;
        String codeNumberType = null;
        for (InnerBidBaseTabulation listObj : listImport) {
            String originalTypeName = listObj.getName();
            String codeNumber = listObj.getCodeNumber();
            if (listObj.getFenLei() == null) {
                if (StringUtils.isNotEmpty(originalTypeName)){
                    if ("增补清单".equals(originalTypeName)){
                        itemName = originalTypeName;
                    }
                    lastNonNullOriginalTypeName = originalTypeName;
                    codeNumberType = codeNumber;
                }
            } else {
                if (lastNonNullOriginalTypeName != null && "增补清单".equals(itemName)) {
                    listObj.setNameType1(itemName);
                    listObj.setNameType2(lastNonNullOriginalTypeName);
                }else {
                    listObj.setNameType1(lastNonNullOriginalTypeName);
                }
            }
            if (listObj.getFenLei() != null) {
                listObj.setFlag(1);
                listObj.setProject(project);
                listObj.setBidType(bidType);
                listObj.setFileName(fileName);
                String fenXiFenLei = "";
                switch (listObj.getFenLei()) {
                    case 1:
                        fenXiFenLei = "高压柜";
                        break;
                    case 2:
                        fenXiFenLei = "高压柜";
                        break;
                    case 3:
                        fenXiFenLei = "低压柜";
                        break;
                    case 4:
                        fenXiFenLei = "母线槽";
                        break;
                    case 5:
                        fenXiFenLei = "变压器";
                        break;
                    case 6:
                    case 7:
                        fenXiFenLei = "高压电缆";
                        break;
                    case 8:
                    case 9:
                        fenXiFenLei = "低压电缆";
                        break;
                    case 10:
                        fenXiFenLei = "电表箱";
                        break;
                    case 11:
                        fenXiFenLei = "配电箱";
                        break;
                    case 12:
                        fenXiFenLei = "电表";
                        break;
                    case 13:
                    case 15:
                    case 18:
                    case 19:
                        fenXiFenLei = "其他";
                        break;
                    case 14:
                        fenXiFenLei = "调试";
                        break;
                    case 16:
                        fenXiFenLei = "电缆通道";
                        break;
                    case 17:
                        fenXiFenLei = "手续费";
                        break;
                    default:
                        fenXiFenLei = "未知";
                        break;
                }
                listObj.setFenXiFenLei(fenXiFenLei);
                listObj.setCodeNumberType(codeNumberType);
                listArrange.add(listObj);
            }
        }

        Integer jieDuan = 1;
        if (bidType == 2){
            jieDuan = 7;
        }
        //计算 工程量、税金、综合单价、综合合价
        for (InnerBidBaseTabulation tabulation : listArrange) {
            //按 “分类、项目名称”来确定内线清单对应全系清单中的内容，匹配到多个数据时取其中一个
            List<AllTabulation> allTabulations = allTabulationService.getRepository().findByFlagAndNameAndFenLei(1, tabulation.getName(), tabulation.getFenLei());
            if (allTabulations == null || allTabulations.size() == 0) {
                tabulation.setModelCodeError(2);
                tabulation.setNeiRongError(2);
            } else {
                Integer correct = 0;
                for (AllTabulation a : allTabulations) {
                    if (StringUtils.isNotEmpty(tabulation.getModelCode())){
                        if (a.getModelCode().equals(tabulation.getModelCode())) {
                            correct++;
                        }
                    }else {
                        if (StringUtils.isEmpty(a.getModelCode())) {
                            correct++;
                        }
                    }
                }
                if (correct == 0) {
                    tabulation.setModelCodeError(1);
                }
                //修正工作内容
                if (allTabulations.get(0).getGongZuoNeiRong().equals(tabulation.getGongZuoNeiRong())) {
                    tabulation.setNeiRongError(1);
                }
            }
            innerBidBaseTabulationService.calculation(tabulation);
        }

        if (listArrange.size() > 0){
            //先删除原来的，再添加
            List<InnerBidBaseTabulation> bidBaseTabulationList = innerBidBaseTabulationService.getRepository().findByFlagAndProjectIdAndBidType(1,projectId,bidType);
            for (InnerBidBaseTabulation bidBaseTabulation : bidBaseTabulationList){
                bidBaseTabulation.setFlag(0);
                innerBidBaseTabulationService.save(bidBaseTabulation);
            }
            if (bidBaseTabulationList.size() > 0){
                innerSummaryService.getRepository().deleteByProjectIdAndJieDuan(bidBaseTabulationList.get(0).getProject().getId(),jieDuan);
            }
        }

        innerBidBaseTabulationService.save(listArrange);

        //清单提取信息计算、保存
        BigDecimal shuiLv = BigDecimal.ZERO;;
        BigDecimal hsBaoJia = BigDecimal.ZERO;
        BigDecimal bhsBaoJia = BigDecimal.ZERO;;
        BigDecimal hsxzBaoJia = BigDecimal.ZERO;;
        for (InnerBidBaseTabulation tabulation : listArrange){
            shuiLv = tabulation.getShuiJinFillIn();
            hsBaoJia = hsBaoJia.add(Optional.ofNullable(tabulation.getTotalPriceOriginal()).orElse(BigDecimal.ZERO));
            hsxzBaoJia = hsxzBaoJia.add(Optional.ofNullable(tabulation.getTotalPrice()).orElse(BigDecimal.ZERO));
        }
        bhsBaoJia = hsBaoJia.divide(shuiLv.add(BigDecimal.ONE), 4,  RoundingMode.HALF_UP);
        TabulationExtracting tabulationExtracting = null;
        List<TabulationExtracting> tabulationExtractings = extractingService.getRepository().findByFlagAndProjectIdAndJieDuanAndInnerOuterType(1,projectId,jieDuan,1);
        for (TabulationExtracting extracting : tabulationExtractings){
            if (extracting.getSupplyCompany() == null) {
                tabulationExtracting = extracting;
            }
        }
        if (tabulationExtracting == null){
            tabulationExtracting = new TabulationExtracting();
            tabulationExtracting.setProject(project);
            tabulationExtracting.setShuiLv(shuiLv);
            tabulationExtracting.setHsBaoJia(hsBaoJia);
            tabulationExtracting.setBhsBaoJia(bhsBaoJia);
            tabulationExtracting.setHsxzBaoJia(hsxzBaoJia);
            tabulationExtracting.setInnerOuterType(1);
            tabulationExtracting.setJieDuan(jieDuan);
        }else {
            tabulationExtracting.setShuiLv(shuiLv);
            tabulationExtracting.setHsBaoJia(hsBaoJia);
            tabulationExtracting.setBhsBaoJia(bhsBaoJia);
            tabulationExtracting.setHsxzBaoJia(hsxzBaoJia);
        }
        extractingService.save(tabulationExtracting);
        //清单关联信息保存
        innerSummaryService.saveCorrelationBd(project,jieDuan,fileName);
        return R.ok();
    }

    @ApiOperation("导出标底、实施标底清单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/exportInnerBd", method = RequestMethod.GET)
    public Result exportInnerBd(Long projectId,Integer bidType) {
        Project project = projectService.findOne(projectId);
        String bidTypeStr = "";
        if (bidType == 1){
            bidTypeStr = "标底";
        }else {
            bidTypeStr = "实施标底";
        }
        String fileName = project.getName() + bidTypeStr;
        XSSFWorkbook workbook = innerBidBaseTabulationService.exportQd(projectId,bidType,fileName);
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/binary;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + URLEncoder.encode(fileName + "-导出.xlsx", "UTF-8"));
            response.setHeader("Pragma", "No-cache");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (workbook != null) {
                    workbook.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail("导出错误");
    }


    @ApiOperation(value = "查询内线标底信息(按分项查询)", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/getBidBaseTabList", produces = {"application/json"}, method = RequestMethod.POST)
    public Result getBidBaseTabList(Long projectId, Integer bidType) {
        HashMap hashMap = new HashMap();
        hashMap.put("project.id", projectId);
        hashMap.put("bidType", bidType);
        List<InnerBidBaseTabulation> innerBidBaseTabulationList = innerBidBaseTabulationService.getListLogic(hashMap, null);

        // 按name属性分组
        Map<String, List<InnerBidBaseTabulation>> nameType1List = innerBidBaseTabulationList.stream()
                .collect(Collectors.groupingBy(InnerBidBaseTabulation::getNameType1));

        List<Map<String, Object>> mapList = new ArrayList<>();
        Integer indexName = 0;
        for (Map.Entry<String, List<InnerBidBaseTabulation>> item : nameType1List.entrySet()) {
            indexName++;
            String nameType1 = item.getKey();
            List<InnerBidBaseTabulation> value = item.getValue();

            InnerBidBaseTabulation newT = innerBidBaseTabulationService.calculationSubtotal(value);
            value.add(0,newT);

            Map<String, Object> tempTabulation = new HashMap<>();
            tempTabulation.put("indexName",indexName);
            tempTabulation.put("nameType1",nameType1);
            tempTabulation.put("value",value);
            mapList.add(tempTabulation);
        }

        return R.ok(mapList);
    }

}
